﻿/*
 *Copyright(C) 2020 by  GYYX All rights reserved.
 *Unity版本：2018.4.23f1 
 *作者:程一峰  
 *创建日期: 2021-04-08 
 *模块说明：
 *版本: 1.2
*/

using Sirenix.OdinInspector;
using System.Collections.Generic;
using UnityEngine;

namespace Warfare.FSM
{
    /// <summary>
    /// 单个状态机文件；
    /// </summary>
    [CreateAssetMenu(fileName = "FSMAsset", menuName = "FSM/FSMAsset", order = 1)]
    public class FSMAsset : SerializedScriptableObject
    {
        [LabelText("描述")]
        [TextArea(1, 2)]
        public string Descripe;

        #region 根节点

        [SerializeField]
        [ShowInInspector]
        [LabelText("根节点")]
        [ReadOnly]
        private FSMRootNode _RootNode;

        /// <summary>
        /// 根节点；
        /// </summary>
        public FSMRootNode RootNode
        {
            get
            {
                if (_RootNode == null)
                    CreateRootNode();
                return _RootNode;
            }
        }

        /// <summary>
        /// 创建根节点；
        /// </summary>
        public void CreateRootNode() { _RootNode = new FSMRootNode(this); }

        #endregion

        /// <summary>
        /// 当前管理的节点；
        /// 没有排列一说；
        /// </summary>
        [LabelText("状态机信息")]
        [SerializeField]
        [Sirenix.Serialization.OdinSerialize]
        public List<FSMNode> ListNodes = new List<FSMNode>();

        /// <summary>
        /// 删除节点；
        /// </summary>
        public void Do_RemoveNode(FSMNode node) { ListNodes.Remove(node); }

        /// <summary>
        /// 当前节点；
        /// </summary>
        public void Do_AddNode(FSMNode node)
        {
            ListNodes.Add(node);
            node.Index = GetIndex(ListNodes);
        }

        /// <summary>
        /// 最大的 Index+1；
        /// </summary>
        private int GetIndex(List<FSMNode> L)
        {
            var maxIndex = 1;
            foreach (var node in L)
            {
                if (node.Index < maxIndex)
                    continue;

                maxIndex = node.Index;
            }
            return maxIndex + 1;
        }

        /// <summary>
        /// 根据下标取节点；
        /// </summary>
        public FSMNode GetNodeByIndex(int index)
        {
            //根节点；
            if (index == 0)
                return RootNode;

            int length = ListNodes.Count;
            for (int i = 0; i < length; i++)
            {
                var node = ListNodes[i];
                if (node.Index == index)
                    return node;
            }
            return RootNode;
        }

    }
}